<?php
declare (strict_types = 1);

namespace app\middleware;
use app\Request;
use think\facade\Config;
use think\Response;

class AllowOriginMiddleware
{
    /**
     * 允许跨域的域名
     * @var string
     */
    protected $cookieDomain;

    protected $header = [
        // 'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

    public function __construct(Config $config)
    {
        $this->cookieDomain = $config::get('cookie.domain', '');
    }
    /**
     * 处理请求,跨域中间件
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next, ?array $header = [])
    {
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        // $this->cookieDomain = Config::get('cookie.domain', '');
        // $header['Access-Control-Allow-Origin'] = '*';
        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }
        $response = $next($request)->header($header);
        return $response;
        // $header = Config::get('cookie.header');
        // $origin = $request->header('origin');
        // if ($request->method(true) == 'OPTIONS') {
        //     $response = Response::create('ok')->code(200)->header($header);
        // } else {
        //     $response = $next($request)->header($header);
        // }
        // $request->filter(['strip_tags', 'addslashes', 'trim']);
        // return $response;

        // $header['Access-Control-Allow-Headers'] = 'content-type,authorization';
        // $header['Access-Control-Allow-Origin'] = '*';

        // if ($request->method(true) == 'OPTIONS') {
        //     $response = Response::create('ok')->code(200)->header($header);
        // } else {
        //     $response = $next($request)->header($header);
        // }
        //$response = $next($request)->header($this->header);
        // $request->filter(['strip_tags', 'addslashes', 'trim']);
        // return $response;
    }
}
